"""
Case Type   : 功能测试
Case Name   : 一主两倍集群stop一个备机，查看控制文件
Create At   : 2025/03/25
Owner       : @chen
Description :
    1.查看集群控制文件：
pg_controldata +data
    2.stop一个备节点
cm_ctl stop -n 2
    3.每个节点查看集群控制文件：
pg_controldata +data
    4.恢复环境：
cm_ctl start -n 2
Expect      :
    1.Database cluster state:               in production
    2.成功
    3.Database cluster state:               in production
    4.成功
History     :
"""

import unittest
import os
import time
from testcase.utils.Logger import Logger
from testcase.utils.Constant import Constant
from testcase.utils.CommonSH import CommonSH
from yat.test import Node
from yat.test import macro
logger = Logger()

class Test_Xlog_Syncretism_0004(unittest.TestCase):
    def setUp(self):
        logger.info(f'--------{os.path.basename(__file__)} start--------')
        self.pri_node = Node('PrimaryDbUser')
        self.sta1_node = Node('Standby1DbUser')
        self.sta2_node = Node('Standby2DbUser')
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.constant = Constant()
    
    def test_shared_storage(self):
        text = '-----step1:查看集群控制文件 expect:in production-----'
        logger.info(text)
        cmd = f'source {macro.DB_ENV_PATH}; pg_controldata +data'
        logger.info(cmd)
        res = self.pri_node.sh(cmd).result()
        logger.info(res)
        self.assertIn('Database cluster state:               in production', 
            res, '校验失败')

        text = '-----step2:stop一个备节点 expect:成功-----'
        logger.info(text)
        res = self.pri_sh.exec_cm_ctl('stop', f'-n 2 -D {macro.DB_INSTANCE_PATH}')
        logger.info(res)
        self.assertIn(self.constant.cm_stop_instance_success_msg, res, '备节点stop失败')

        text = '-----step3:每个节点查看集群控制文件 expect:in production-----'
        logger.info(text)
        logger.info('-----主节点校验-----')
        logger.info(cmd)
        res = self.pri_node.sh(cmd).result()
        logger.info(res)
        self.assertIn('Database cluster state:               in production', 
            res, '主节点校验失败')
        logger.info('-----备1节点校验-----')
        logger.info(cmd)
        res = self.sta1_node.sh(cmd).result()
        logger.info(res)
        self.assertIn('Database cluster state:               in production', 
            res, '备1节点校验失败')
        logger.info('-----备2节点校验-----')
        logger.info(cmd)
        res = self.sta2_node.sh(cmd).result()
        logger.info(res)
        self.assertIn('Database cluster state:               in production', 
            res, '备2节点校验失败')
    
    def tearDown(self):
        text = '-----step4:恢复环境 expect:成功-----'
        logger.info(text)
        res = self.pri_sh.exec_cm_ctl('start', f'-n 2 -D {macro.DB_INSTANCE_PATH}')
        logger.info(res)
        self.assertIn(self.constant.cm_start_node_success_msg, res, '主节点stop失败')
        logger.info(f'-----{os.path.basename(__file__)} end-----')